using AdminApi.Domain;
using AdminApi.Dto;
using AdminApi.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace AdminApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class BlogsController : ControllerBase
{
    // 从数据库查询数据
    // private readonly AdminDbContext _db;
    private readonly IRepository<Blogs> _repBlogs; 
    // public BlogsController(AdminDbContext db)
    // {
    //     _db = db;
    // }
    public BlogsController(IRepository<Blogs> repBlogs)
    {
        _repBlogs = repBlogs;
    }

    // 查询所有内容
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        // var blogs = _db.Blogs.ToList();
        var blogs = await _repBlogs.GetAllAsync();
        return Ok(ApiResultDto<List<Blogs>>.Success(blogs,"查询列表成功"));
        // return Ok(blogs);  // 用于生成一个状态码为200（表示请求成功）的HTTP响应
    }
    // 查询单个数据
    [HttpGet("{id}")]
    public async Task<IActionResult> GetId(Guid id)
    {
        var blog = await _repBlogs.GetByIdAsync(id);
        if (blog == null)
        {
            return NotFound();
        }
        return Ok(ApiResultDto<Blogs>.Success(blog));
    }

    // 新增
    [HttpPost]
    public async Task<IActionResult> Post(BlogCreateDto blogCreateDto)
    {
        var blog = new Blogs {Title=blogCreateDto.Title,Author=blogCreateDto.Author,Content=blogCreateDto.Content};
        // var obj = _db.Blogs.Add(blog).Entity;
        // _db.SaveChanges();
        var obj = await _repBlogs.CreateAsync(blog);
        return Ok(ApiResultDto<Blogs>.Success(blog,"新增成功"));

        // blog.Id = (_db.Blogs.LastOrDefault()?.Id ?? 0)+1;
        // _db.Blogs.Add(blog);
        // return Ok(new {Code=1000,Data=blog,Msg="新增成功"});
        // return CreatedAtAction(nameof(GetId), new { id = blog.Id }, blog);
        // 是一个用于生成HTTP响应的方法，它返回一个状态码为201（Created）的响应，并且包含一个指向新创建资源的URL
    }

    // 编辑
    [HttpPut("{id}")]
    public async Task<IActionResult> Put(Guid id, BlogCreateDto blogCreateDto)
    {
        var blog = await _repBlogs.GetByIdAsync(id);
        if (blog == null)
        {
            return NotFound();
        }
        blog.Title = blogCreateDto.Title;
        blog.Author = blogCreateDto.Author;
        blog.Content = blogCreateDto.Content;

        // _db.Blogs.Update(blog);
        // _db.SaveChanges();
        await _repBlogs.UpdateAsync(blog);
        return Ok(ApiResultDto<Blogs>.Success(blog,"编辑成功"));
        // return NoContent(); // 返回状态码204（No Content），表示请求成功，但没有返回内容
    }

    // 删除
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        var blog = await _repBlogs.GetByIdAsync(id);
        if (blog == null)
        {
            return NotFound();
        }
        // _db.Blogs.Remove(blog);
        // _db.SaveChanges();
        await _repBlogs.DeleteAsync(blog);
        return Ok(ApiResultDto<Blogs>.Success(blog,"删除成功"));
    }
}